/*
 * Copyright 2025 author or author.
 * SPDX-License-Identifier: Apache-2.0
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.jcwang.commons.tools.util.net;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.management.Query;
import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Set;

/**
 * 服务器信息工具类
 *
 * @author 王金城
 **/
public class ServerInfoUtils {

    private static final Logger logger = LoggerFactory.getLogger(ServerInfoUtils.class);

    /**
     * 获取服务器IP
     *
     * @return IP地址 如果异常会返回 ""
     * @author 王金城
     */
    public static String getServerIp() {
        try {
            return InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            logger.error("获取服务器IP异常", e);
            return "";
        }
    }

    /**
     * 获取端口号
     *
     * @return 端口号 出现异常返回空字符串
     * @author 王金城
     */
    public static String getServerPort() {
        try {
            MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
            Set<ObjectName> objs = mbs.queryNames(new ObjectName("*:type=Connector,*"),
                    Query.match(Query.attr("protocol"), Query.value("HTTP/1.1")));
            return objs.iterator().next().getKeyProperty("port");
        } catch (MalformedObjectNameException e) {
            logger.error("获取服务器端口号异常", e);
        }
        return "";
    }

}
